<template>
  <div class="">
    <my-header>
      <span>郑州</span>
    </my-header>
    <my-input v-model="keyword"></my-input>
    <van-button type="primary" @click="search">搜索</van-button>

    <ul class="result" style="margin-bottom: 30px">
      <h5>搜索结果</h5>
      <li v-for="(item, index) in result" :key="index" @click="gotoList(item)">
        {{ item.name }}
      </li>
    </ul>

    <ul v-if="result.length <= 0 && history.length != 0" class="result">
      <h5>
        历史记录
        <van-button type="primary" @click="clear">清空历史记录</van-button>
      </h5>
      <li v-for="(item, index) in history" :key="index" @click="gotoList(item)">
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>

<script>
import { ref, reactive, toRefs } from "vue";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import myHeader from "../components/myHeader.vue";
import myInput from "../components/myInput.vue";
import { getSearch } from "../utils/ele";
export default {
  setup(props, ctx) {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const data = reactive({
      keyword: "",
      result: [],
      history: JSON.parse(localStorage.getItem("history")) || [],
      //取本地存储里的历史记录
    });

    const search = () => {
      getSearch(data.keyword).then((res) => {
        data.result = res;
      });
    };
    //搜索

    const gotoList = (item) => {
      data.history.splice(4, 1);
      data.history.unshift(item);
      //最多添加五条

      localStorage.setItem("history", JSON.stringify(data.history));
      //存本地存储

      router.push({
        path: "/about",
        query: {
          latitude: item.latitude,
          longitude: item.longitude,
        },
      });
    };
    //跳转商圈 还有存历史记录

    const clear = () => {
      data.history = [];
      localStorage.removeItem("history");
    };
    //清空历史记录
    return { ...toRefs(data), gotoList, search, clear };
  },
  components: {
    myHeader,
    myInput,
  },
};
</script>

<style lang="scss">
.result {
  li {
    height: 40px;
    border: 1px solid #ccc;
  }
}
</style>
